package org.sft.web.wx.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author benxi
 *
 *         2016年6月30日
 */
@Controller
@RequestMapping(value = "wx")
public class WXController {
	private Logger log = Logger.getLogger(getClass());

	/**
	 * 微信服务器校验接口
	 * 
	 * @param signature
	 * @param timestamp
	 * @param nonce
	 * @param echostr
	 * @return
	 * @throws IOException 
	 */
	@ResponseBody
	@RequestMapping(value = "check", method = { RequestMethod.GET })
	public void checkCode(HttpServletResponse response,String signature, String timestamp, String nonce, String echostr) throws IOException {

		log.debug(".......................................................");
		log.debug("signature:" + signature);
		log.debug("timestamp:" + timestamp);
		log.debug("nonce:" + nonce);
		log.debug("echostr:" + echostr);
		log.debug(".......................................................");
		PrintWriter out=response.getWriter();
		if (CheckUtil.checkSignature(signature, timestamp, nonce)) {
			log.debug("校验成功");
			out.println(echostr);
		} else {
			
		}
	}
	@RequestMapping
	public void test0(){
		
	}

	

}

class CheckUtil {
	public static boolean checkSignature(String signature, String timestamp, String nonce) {
		String token = "qingmuyu";
		String[] arr = new String[] { token, timestamp, nonce };// 排序
		Arrays.sort(arr);
		StringBuffer content = new StringBuffer();
		for (String str : arr) {
			content.append(str);
		}
		String sha1str=SHA(content.toString());//加密
		return sha1str.equals(signature);
	}

	/**
	 * sha1加密
	 * @param decript
	 * @return
	 */
	public static String SHA(String decript) {
		try {
			MessageDigest digest = java.security.MessageDigest.getInstance("SHA");
			digest.update(decript.getBytes());
			byte messageDigest[] = digest.digest();
			// Create Hex String
			StringBuffer hexString = new StringBuffer();
			// 字节数组转换为 十六进制 数
			for (int i = 0; i < messageDigest.length; i++) {
				String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
				if (shaHex.length() < 2) {
					hexString.append(0);
				}
				hexString.append(shaHex);
			}
			return hexString.toString();

		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return "";
	}

}
